<template>
	<view class="login">
		<view class="title">
			赊货签
		</view>
		<uni-forms v-if="isAPP" ref="form" :modelValue="formData" label-width="80px" :rules="rules">
			<uni-forms-item label="手机号" name="userName">
				<input type="number" v-model="formData.userName" placeholder="请输入手机号" />
			</uni-forms-item>
			<p></p>
			<uni-forms-item label="密码" name="password">
				<input type="password" v-model="formData.password" placeholder="请输入密码" />
			</uni-forms-item>
			<!-- 暂时不删除 -->
			<!-- 	<uni-forms-item label="验证码" name="password">
				<view class="" style="display: flex;justify-content: space-between;">
					<input type="password" v-model="formData.password" placeholder="请输入验证码" style="flex: 6;" />
					<text style="flex: 4;" @click="codeChange">{{!codeTime?'获取验证码':codeTime+'s后重发'}}</text>
				</view>
			</uni-forms-item> -->
			<p></p>

			<button class="button" type="primary" @click="login">登 录</button>
			<view class="flexBox">
				<view>
					<checkbox-group @change="rememberPass">
						<label>
							<checkbox value="pass" :checked="remember" />记住密码
						</label>
					</checkbox-group>
				</view>
				<text @click="toPassword">忘记密码</text>
			</view>

			<view v-show="!showCode" class="flexBox" style="margin-bottom: 40rpx;">
				<checkbox-group @change="changeAgree">
					<label>
						<checkbox value="a" :checked="agree" />
						我已阅读并同意
					</label>
					<text @click="openAgreement" style="color: #b051ff">《用户服务协议》、</text>
					<text @click="openUse" style="color: #b051ff;">《隐私政策》</text>
				</checkbox-group>
				<!-- <text @click="openAgreement" style="color: #b051ff">《用户服务协议》、</text> 
				<text @click="openUse" style="color: #b051ff">隐私政策</text> -->
			</view>
		</uni-forms>
		<view v-if="isAPP" class="funArea" style="display: flex;flex-direction: column;">
			<text @click="toRegister">没有账号? 立即注册</text>
			<!-- <text v-show="!isWeixinLogin" @click="otherLogin" style="margin-top: 20rpx;color: royalblue;"> <text
					style="border-bottom: 1px solid #587EF2 ;">使用其它账号登录</text> </text>
			<uni-transition ref="ani" custom-class="transition" :mode-class="modeClass" :show="isWeixinLogin">
				<view class="" v-show="isWeixinLogin" style="padding-top: 30rpx;" @click="wecartChangeLogin">
					<image style="width: 15%;height:100rpx" src="../../static/Login/weixin.png" mode=""></image>
				</view>
			</uni-transition> -->
			<!-- #ifdef MP-WEIXIN -->
			<view style="margin-top: 10px;">

				<text style="border-bottom: 1px solid #fff;" @click="isAPP = false">快速登录</text>
			</view>
			<!-- #endif -->
		</view>
		<view class="" v-else>
			<button type="primary" @click="wxLogin"
				style="width: 400rpx;margin-top: 300rpx;box-shadow: 0px 0px 10px #888;border-radius: 100rpx;font-size: 20px;font-weight: bold;">
				快 速 登 录</button>
			<button type="primary" @click="isAPP = true"
				style="width: 400rpx;margin-top: 100rpx;box-shadow: 0px 0px 10px #888;border-radius: 100rpx;font-size: 20px;font-weight: bold;">
				账 号 登 录</button>
		</view>
		<view v-if="!isAPP" class="flexBox" style="position: fixed;bottom: 40rpx;font-size: 12px;">
			<checkbox-group @change="changeAgree">
				<label>
					<checkbox value="a" :checked="agree" />
					我已阅读并同意
				</label>
				<text @click="openAgreement" style="color: #b051ff">《用户服务协议》、</text>
				<text @click="openUse" style="color: #b051ff;">《隐私政策》</text>
			</checkbox-group>
		</view>
		<privacyPopup></privacyPopup>
	</view>
</template>

<script>
	import {
		regPhone
	} from '../../utils/regExp.js'
	import privacyPopup from '@/components/privacy-popup/privacy-popup.vue'
	export default {
		components: {
			privacyPopup
		},
		data() {
			return {
				isAPP: false,
				isWeixinLogin: false,
				modeClass: 'slide-right',
				codeTime: 0,
				showCode: false,
				remember: false,
				agree: true, // 是否同意条款
				formData: {
					userName: '',
					password: ''
				},
				rules: {
					userName: {
						rules: [{
							required: true,
							errorMessage: '请填写手机号',
						}, {
							validateFunction: (rule, value, data, callback) => {
								if (!regPhone.test(value)) return callback('手机号格式错误')
								return true
							}
						}]
					},
					password: {
						rules: [{
							required: true,
							errorMessage: '请填写密码',
						}]
					},
				},
				weixinAuthService: {},
				// 是否认证
				flag: false,
				// 用户信息
				UserInfo: {}
			}
		},
		onLoad() {
			if (!uni.getStorageSync('agree')) this.agree = false
			// #ifdef MP-WEIXIN
			this.isAPP = false
			let openId = uni.getStorageSync('openId')
			if (openId) {
				this.openIdLogin(openId)
				return
			}
			// #endif
			let pass = uni.getStorageSync('pass')
			if (pass) {
				this.formData = pass
				this.loginApi()
			}
		},
		onShow() {
			this.isWeixinLogin = false
		},
		methods: {
			// 快速登录
			wxLogin() {
				if (!this.agree) {
					uni.showToast({
						icon: 'none',
						title: '请阅读并同意使用条款后进行登录'
					})
					return
				}
				uni.login({
					provider: 'weixin',
					success: (res) => {
						console.log(res);
						this.getOpenId(res.code)
					},
					fail: (err) => {
						console.log(err);
						uni.showToast({
							icon: 'none',
							title: '微信登录失败,请重新尝试'
						})
					}
				})
			},
			// 通过Code获取微信id
			getOpenId(code) {
				this.$http('get', '/Base_Manage/Home/GetWxOpenId?code=' + code).then(res => {
					console.log("<<<<" + JSON.parse(res.Data).openid)
					uni.setStorageSync('openId', JSON.parse(res.Data).openid)
					this.openIdLogin(JSON.parse(res.Data).openid)
				})
			},
			// 通过openId进行登录
			openIdLogin(openId) {
				this.$http('post', '/Base_Manage/Home/WxLogin', {
					"OpenId": openId
				}).then(res => {
					if (res.Data.State) {
						uni.setStorage({
							data: 'Bearer ' + res.Data.Token,
							key: 'token',
							success: () => {
								this.op()
							}
						})
						// 登录失败去绑定
					} else uni.navigateTo({
						url: '/pages/Login/WXRegister?openId=' + openId
					})
				})
			},
			handleThirdLoginApp() {
				var that = this;
				uni.getProvider({
					service: 'oauth',
					success: function(res) {
						if (~res.provider.indexOf('weixin')) {
							uni.login({
								provider: 'weixin',
								success: function(loginRes) {
									console.log('login', loginRes)
									// loginRes 包含access_token，expires_in，openid，unionid等信息
									//这里只需要把这些数据传递给后台，让后台去请求微信的接口拿到用户信息就可以了，
									//然后返回登录状态
									that.getApploginData(loginRes); //请求登录接口方法
								},

								fail: function(res) {
									that.$refs.uToast.show({
										title: '微信登录失败',
										type: 'warning'
									});
								}
							});
						}
					}
				});
			},
			otherLogin() {
				this.isWeixinLogin = !this.isWeixinLogin
			},
			// 使用其它账号登录
			wecartChangeLogin() {
				var that = this;
				uni.getProvider({
					service: 'oauth',
					success: function(res) {
						if (~res.provider.indexOf('weixin')) {
							uni.login({
								provider: 'weixin',
								success: function(loginRes) {
									// loginRes 包含access_token，expires_in，openid，unionid等信息
									//这里只需要把这些数据传递给后台，让后台去请求微信的接口拿到用户信息就可以了，
									//然后返回登录状态
									that.getApploginData(loginRes); //请求登录接口方法
								},

								fail: function(res) {
									uni.showToast({
										title: '微信登录失败' + res.Msg,
										type: 'warning'
									})
								}
							});
						}
					}
				});
			},
			//请求登录接口方法

			getApploginData(data) {
				var that = this;
				//这边是前端自己去调微信用户信息的接口，根据接口需要请求，如果不需要前端去获取的话就交给后端，可省去次操作
				uni.request({
					url: 'https://api.weixin.qq.com/sns/userinfo?access_token=' + data.authResult.access_token +
						'&openid=' + data.authResult.openid,
					method: 'GET',
					dataType: 'json',
					header: {
						'content-type': 'application/x-www-form-urlencoded' // 默认值
					},

					success(res) {
						console.log('【登录回调啾啾啾】', res);
						//前端调用微信接口，获取到微信用户的基本信息，传递给后台
						that.$http('post', '/Base_Manage/Home/WxLogin', {
							OpenId: res.openid
						}).then(result => {
							console.log('是否微信登录成功', result)
							// uni.reLaunch({
							// 	url:"/pages/Home/Home"
							// })
							// if (result.Success) {
							// 	if(result.Data.State){

							// 	}else{
							// 		uni.showToast({
							// 			title:'请绑定手机号',
							// 			icon:'none'
							// 		})
							// 	}
							// 	// uni.showToast({
							// 	// 	icon: 'none',
							// 	// 	title: result.Msg
							// 	// })
							// 	// this.showCode = true
							// } else uni.showToast({
							// 	icon: 'none',
							// 	title: result.Msg
							// })
						})
						// that.$api.wxloginThred({
						// 	unionid: data.authResult.unionid,
						// 	image: res.data.headimgurl,
						// 	nickname: res.data.nickname,
						// }).then(res => {
						// 	console.log(res)
						// 	if (res.statusCode == 200) {
						// 		uni.setStorageSync('userInfo', JSON.stringify(res.data));
						// 		uni.setStorageSync('logined', 1);
						// 		// that.$store.commit('SET_STATE', ['logined', true]);
						// 		// that.$store.commit('SET_STATE', ['userInfo', res.data]);
						// 		uni.showToast({
						// 			title: '登陆成功',
						// 			duration: 2000
						// 		});
						// 		//登录成功 跳转到首页
						// 		that.checkFirst()
						// 	}
						// });
					},
					fail() {
						uni.showToast({
							title: '微信登录失败',
							icon: 'none'
						})
					}
				});
			},
			// 发送验证码
			codeChange() {
				console.log('点击发送验证码', this.disabled)
				this.$refs.form.validate().then(res => {
					this.$http('post', '/BO/CustomerLinkman/CusLogincmscode?Phone=' + this.formData.userName).then(
						res => {
							uni.hideLoading()
							if (res.Success) {
								uni.showToast({
									title: "验证码已发送",
									icon: "none"
								})
								if (this.codeTime > 0) {
									uni.showToast({
										title: '不能重复获取',
										icon: "none"
									});
									return;
								} else {
									this.codeTime = 60
									let timer = setInterval(() => {
										this.codeTime--;
										console.log('获取递减', this.codeTime)
										if (this.codeTime < 1) {
											clearInterval(timer);
											this.codeTime = 0
										}
									}, 1000)
								}

							} else uni.showToast({
								icon: 'none',
								title: res.Msg
							})
						})
					// this.loginApi()

				}).catch(err => {
					console.log(err);
				})


			},
			openAgreement() {
				uni.navigateTo({
					url: '/pages/User/customerPage?Type=1'
				})
			},
			openUse() {
				uni.navigateTo({
					url: '/pages/webView/Use'
				})
			},
			changeAgree(e) {
				if (e.detail.value.length > 0) this.agree = true
				else this.agree = false
			},
			rememberPass(e) {
				if (e.detail.value.length > 0) this.remember = true
				else this.remember = false
			},
			// 注册
			toRegister() {
				console.log('注册')
				uni.navigateTo({
					url: '/pages/Login/Register'
				})
			},
			//忘记密码
			toPassword() {
				uni.navigateTo({
					url: '/pages/Login/Password'
				})
			},
			// 登陆
			login() {
				if (!this.agree) {
					uni.showToast({
						icon: 'none',
						title: '请阅读并同意使用条款后进行登录'
					})
					return
				}
				this.$refs.form.validate().then(res => {
					// 登录校验买家还是卖家   暂时不删除 后续㱙需要打开
					// this.$http('post', '/Base_Manage/Base_User/BuyerCheckLogin?Phone=' + this.formData.userName)
					// 	.then(res => {
					// 		uni.hideLoading()
					// 		if (res.Success) {
					// 			console.log('是否继续', res)

					// 			if (res.Data == true) {
					// 				// 登录校验
					// 				this.loginApi()
					// 			} else {
					// 				uni.showToast({
					// 					title: "无法登录",
					// 					icon: "none"
					// 				})
					// 			}

					// 		} else uni.showToast({
					// 			icon: 'none',
					// 			title: res.Msg
					// 		})
					// 	})

					this.loginApi()

				}).catch(err => {
					console.log(err);
				})

			},
			loginApi() {
				uni.showLoading()
				// this.$http('post', '/Base_Manage/Home/SubmitLogin', this.formData).then(res => {
				this.$http('post', '/Base_Manage/Home/SubmitLogins', this.formData).then(res => {
					uni.hideLoading()
					if (res.Success) {
						if (this.remember) {
							uni.setStorageSync('pass', this.formData)
						}
						uni.setStorageSync('agree', true)
						uni.setStorage({
							data: 'Bearer ' + res.Data,
							key: 'token',
							success: () => {
								this.op()
							}
						})
						// uni.switchTab({
						// 	url: '/pages/Home/Home'
						// })
					} else uni.showToast({
						icon: 'none',
						title: res.Msg + '或无权登录'
					})
				})
			},
			// 用户信息
			op() {
				this.$http('post', '/Base_Manage/Home/GetOperatorInfo').then(res => {
					if (res.Success) {
						console.log('获取用户信息loginloginloginloginlogin', res.Data)
						this.UserInfo = res.Data.UserInfo
						uni.setStorageSync('userInfo', res.Data.UserInfo)
						uni.switchTab({
							url: '/pages/Home/Home'
						})

					}
				})
			},


		}
	}
</script>

<style lang="scss" scoped>
	::v-deep.uni-forms {
		background-color: #fff;
		display: flexbox;
		border-radius: 17px;
		padding: 20px 0;
	}

	::v-deep.uni-forms-item {
		color: #000;
		padding: 10rpx 20rpx 10rpx 33rpx;
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
	}

	::v-deep.uni-forms-item__label {
		display: flex;
		flex-direction: row;
		align-items: center;
		text-align: left;
		font-size: 16px;
		font-weight: bold;
		color: #7d8084;
		height: 36px;
		padding: 0 12px 0 0;
		vertical-align: middle;
		flex-shrink: 0;
		box-sizing: border-box;
	}

	::v-deep.uni-forms-item__error {
		color: #f56c6c;
		font-size: 12px;
		line-height: 2.9;
	}


	.active {
		color: #8264FF
	}

	.flex {
		display: flex;
		margin-top: 40rpx;
		text-align: center;
		color: #a6a6a6;
		font-size: 15px;
		margin-left: 20px;
	}

	.login {
		padding: 40rpx;
		width: 100%;
		height: 100%;
		background: $LoginBG no-repeat center center fixed;
		// background: $LoginBG no-repeat center center fixed;
		background-size: cover;
		box-sizing: border-box;

		.flexBox {
			margin-top: 40rpx;
			box-sizing: border-box;
			padding: 10rpx 40rpx;
			display: flex;
			justify-content: space-between;
		}

		.title {
			text-align: center;
			font-size: 70rpx;
			font-weight: bolder;
			color: #fff;
			// margin-top: 30rpx;
			// margin-bottom: 3%;
			line-height: 4;
		}

		.textH {
			text-align: center;
			font-size: 40rpx;
			font-weight: 500;
			color: #fff;
			margin-bottom: 90rpx;
		}


		p {
			border-bottom: 1px solid #d5d5d5;
			width: 92%;
			margin: 0 auto;
			margin-bottom: 5%;
			margin-top: -2%;
		}

		h6 {
			text-align: right;
			font-size: 15px;
			font-weight: bold;
			color: #6d7073;
			padding: 0 60rpx;

		}

		.button {
			width: 90%;
			border-radius: 100rpx;
			font-size: 20px;
			font-weight: bold;
			margin-top: 40rpx;
			background: linear-gradient(to left, #b5ceff, #3b6dff);
		}

		.funArea {
			margin-top: 30rpx;
			text-align: center;
			color: #fff;
			font-size: 15px;
			font-weight: bold;
		}
	}
</style>